package mallcart

import (
	"context"
	"strconv"
	"strings"

	"mall/common/cachex"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/lib/shoppingcart"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/order/rpc/orderclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteShoppingCartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteShoppingCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteShoppingCartLogic {
	return &DeleteShoppingCartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteShoppingCartLogic) DeleteShoppingCart(
	req *types.DeleteShoppingCartReq,
	headers *[]*types.Header,
) (resp *types.BaseMsgResp, err error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	if len(req.SkuIds) == 0 && req.Clear == nil {
		return &types.BaseMsgResp{
			Msg: "删除成功",
		}, nil
	}

	shoppingCart := shoppingcart.NewShoppingCart(l.ctx, l.svcCtx, cachex.ForumShoppingCart)

	var clear *uint32
	var skuIds []string
	if req.Clear != nil && *req.Clear {
		_, err = shoppingCart.Clear(strconv.FormatInt(int64(userId), 10))
		if err != nil {
			return nil, err
		}

		clear = pointy.GetPointer(uint32(1))
	} else if len(req.SkuIds) > 0 {
		for _, skuId := range req.SkuIds {
			if skuId > 0 {
				skuIds = append(skuIds, strconv.FormatInt(int64(skuId), 10))
			}
		}
		if len(skuIds) > 0 {
			_, err = shoppingCart.BatchDelete(strconv.FormatInt(int64(userId), 10), skuIds)
			if err != nil {
				return nil, err
			}
		}
	}

	if clear != nil || len(skuIds) > 0 {
		_, err = l.svcCtx.OrderRpc.DeleteShoppingCart(l.ctx, &orderclient.DeleteShoppingCartReq{
			UserId: pointy.GetPointer(userId),
			SkuIds: pointy.GetPointer(strings.Join(skuIds, ",")),
			Clear:  clear,
		})
		if err != nil {
			logx.Errorw("DeleteShoppingCart err", logx.Field("detail", err.Error()))
			return &types.BaseMsgResp{
				Msg: "删除失败",
			}, nil
		}
	}

	return &types.BaseMsgResp{
		Msg: "删除成功",
	}, nil
}
